/*
 * @Author: lsjweiyi
 * @Date: 2023-02-10 20:44:01
 * @LastEditors: lsjweiyi
 * @LastEditTime: 2023-09-12 18:41:14
 * @Description: 日志中间件，每个请求进来都会生成唯一日志id，在多微服务时很方便链路追踪
 * Copyright (c) 2023 by lsjweiyi, All Rights Reserved.
 */
package middleware

import (
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"github.com/yitter/idgenerator-go/idgen"
)

// 为一次请求生成唯一的日志id，方便微服务的日志追踪 中间件
func LogHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		// option方式不是实际的请求，所以这里没必要生成日志id
		if c.Request.Method == http.MethodOptions {
			c.Next()
			return
		}
		requestId := int(idgen.NextId())
		c.Header("Log-Id", strconv.Itoa(requestId)) // 设置response的header
		c.Next()
	}
}
